package com.bfly.mall.product.service.impl;

import com.bfly.common.json.JsonUtil;
import com.bfly.core.base.service.BaseServiceImpl;
import com.bfly.mall.product.dao.ProductSpeAttrMapper;
import com.bfly.mall.product.entity.ProductSpeAttr;
import com.bfly.mall.product.dto.ProductSpeAttrFormDTO;
import com.bfly.mall.product.service.IProductSpeAttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author 长沙商脉科技有限公司
 * @date 2020/9/21 12:32
 */
@Service
public class ProductSpeAttrServiceImpl extends BaseServiceImpl<ProductSpeAttr, Integer> implements IProductSpeAttrService {


    @Autowired
    private ProductSpeAttrMapper speAttrMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void merge(int productId, List<ProductSpeAttrFormDTO> formDTO) {
        // 先清除产品规格属性 再保存
        speAttrMapper.clearSpeAttrs(productId);

        formDTO.forEach(dto -> {
            ProductSpeAttr attr = new ProductSpeAttr();
            attr.setName(dto.getName());
            attr.setSeq(dto.getSeq());

            String json = JsonUtil.toJsonFilterForArray(dto.getData()).toJSONString();
            attr.setData(json);

            attr.setProductId(productId);
            attr.setCreateDate(new Date());
            attr.setUpdateDate(attr.getCreateDate());
            super.save(attr);
        });
    }
}